package com.biglead.demo.security;

import com.alibaba.fastjson.JSONObject;
import com.biglead.demo.pojo.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class JWTAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JWTGenerator tokenGenerator;
    @Autowired
    private CustomUserDetailsService customUserDetailsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的 token 信息
        String token = getJWTFromRequest(request);
        //校验token
        if(StringUtils.hasText(token) && tokenGenerator.validateToken(token)) {
            //解析 token 中的用户信息 （用户的唯一标识 ）
            String username = tokenGenerator.getUsernameFromJWT(token);

            UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null,
                    userDetails.getAuthorities());
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            //获取用户信息
            ValueOperations<String, UserInfo> operations = redisTemplate.opsForValue();
            UserInfo userInfo = operations.get(token);
            if(userInfo==null){
                Map<String,Object> map = new HashMap<>();
                map.put("code",403);
                map.put("message","登录过期，重新登录");
                response.getWriter().print(JSONObject.toJSONString(map));
                return;
            }

            //自定义Request
            HttpServletRequest req = (HttpServletRequest) request;

            XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper(req);
            //添加自定义头
            xssRequest.putHeader("userId", userInfo.getUserId().toString());
            xssRequest.putHeader("userName", userInfo.getUserName().toString());

            filterChain.doFilter(xssRequest, response);
            return;
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 就是校验请求头的一种格式 可以随便定义
     * 只要可以解析 就可以
     * @param request
     * @return
     */
    private String getJWTFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7, bearerToken.length());
        }
        return null;
    }
}